package com.ailk.kbi.kbiwarden.wsi.service;

import javax.jws.WebService;

import com.ailk.kbi.kbiwarden.wsi.exception.WSI_ERROR;
import com.ailk.kbi.kbiwarden.wsi.exception.WsiException;
import com.ailk.kbi.kbiwarden.wsi.type.request.AuthInfoType;
import com.ailk.kbi.kbiwarden.wsi.type.request.ConditionsType;
import com.ailk.kbi.kbiwarden.wsi.type.response.ResultType;
import com.ailk.kbi.kbiwarden.wsi.util.AsynUtil;
import com.ailk.kbi.kbiwarden.wsi.util.SessionHandler;
import com.ailk.kbi.kbiwarden.wsi.util.SynUtil;
import com.ailk.kbi.kbiwarden.wsi.util.SystemUtil;
import com.ailk.kbi.kbiwarden.wsi.util.test.InterfaceTestUtil;
import com.ailk.kbi.kbiwarden.wsi.vo.SessionVO;

@WebService(endpointInterface = "com.ailk.kbi.kbiwarden.wsi.service.Query", serviceName = "QueryService", portName = "QueryPort")
public class QueryService implements Query {
	private SystemUtil securityUtil = new SystemUtil();

	public ResultType getData(AuthInfoType login, String table, ConditionsType conditions) {
		ResultType result;
		try {
			doSecurity(login, table);
			result = SynUtil.getSynDate(securityUtil.getSchema(table), securityUtil.getTable(table), conditions);
		} catch (Throwable t) {
			result = throwableHandler(t);
		}

		return result;
	}

	public ResultType getDataAsyn(AuthInfoType login, String table,
			ConditionsType conditions) {
		/* 与订购方式的区别在于不会发出完成通知 */
		return getDataSubscribe(login, table, conditions, null);
	}

	public ResultType getDataSubscribe(AuthInfoType login, String table,
			ConditionsType conditions, String notifyAddress) {
		ResultType result = new ResultType();
		try {
			doSecurity(login, table);
//			String resultXML = AsynUtil.startAsynData(login, securityUtil.getSchema(table), securityUtil.getTable(table), conditions, notifyAddress);
//			result.setSuccess(true);
//			result.setResultXML(resultXML);
		} catch (Throwable t) {
			result = throwableHandler(t);
		}
		return result;
	}

	public ResultType getDataResult(AuthInfoType login, String sessionId) {
		ResultType result = new ResultType();
		try {
			securityUtil.login(login);
//			SessionVO session = SessionHandler.getSession(sessionId);
//			if (!login.getUserName().equalsIgnoreCase(session.getUserName())) {
//				throw new Exception("访问会话错误");
//			}
//
//			result.setResultXML(AsynUtil.getDataXML(sessionId));
//			result.setSuccess(true);
		} catch (Throwable t) {
			result = throwableHandler(t);
		}
		return result;
	}

	private void doSecurity(AuthInfoType login, String operationName) throws Exception {
		securityUtil.login(login);
		securityUtil.security(login.getUserName(), operationName);
	}

	private ResultType throwableHandler(Throwable t){
		ResultType result;
		if(t.getClass().equals(WsiException.class)){
			result = ((WsiException)t).getWsiError();
		}
		else{
			result = WSI_ERROR.ER_999_UNKNOWN;
			result.setDescription(t.getMessage());
		}
		return result;
	}
}